<template>
  <el-dialog v-model="isDialogShow" title="添加人员" width="500" @closed="handleDialogClosed">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="门店">
        <el-text>{{ shopName }}</el-text>
      </el-form-item>
      <el-form-item label="人员" prop="shopUserIds">
        <employee-table-for-select v-model="form.shopUserIds" filter="shop" multiple type="userIds"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        <el-button @click="handleCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import {ref} from "vue";
import {ElForm, ElMessage} from "element-plus";
import {isAxiosError} from "axios";
import {addShopUserToShop} from "@/api/shopUser";
import EmployeeTableForSelect from "@/components/table/EmployeeTableForSelect.vue";

const isDialogShow = defineModel<boolean>()
const props = defineProps<{ shopId: number, shopName: string }>()
const emit = defineEmits<{
  addSuccess: []
  success: []
}>()

const form = ref<{ shopUserIds?: string[] }>({})
const formRef = ref<InstanceType<typeof ElForm>>()
const rules = {
  shopUserIds: [
    {
      required: true,
      message: "人员不能为空",
      trigger: "change"
    },
  ],
}

function handleCancelClick() {
  isDialogShow.value = false
}

async function handleConfirmClick() {
  formRef.value?.validate(async (isValid) => {
    if (isValid) {
      try {
        if (form.value.shopUserIds !== undefined) {
          const {code, msg} = await addShopUserToShop(props.shopId, form.value.shopUserIds)
          switch (code) {
            case "200": {
              ElMessage.success('添加成功');
              emit("addSuccess")
              emit("success")
              break
            }
            case "501": {
              ElMessage.error(msg)
              emit("addSuccess")
              emit("success")
              break
            }
            case "502": {
              ElMessage.error(msg)
              break
            }
          }
          isDialogShow.value = false;
        }
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  })
}

async function handleDialogClosed() {
  formRef.value?.resetFields()
  form.value.shopUserIds = undefined
}
</script>
